/**
 * http 工具
 */
var Http = cc.Class.extend({
    /**
     * http get请求
     * @param {String} url 请求地址
     * @param {Function} cbSucc 成功回调
     * @param {Function} [cbFail] 失败回调
     * @param {{}} [options] 请求配置
     * @public
     */
    get: function (url, cbSucc, cbFail, options) {
        cc.log('http.get()' + url);
        var flag = false;
        var xhr = cc.loader.getXMLHttpRequest();
        xhr.open('GET', url);
        if (cc.sys.isNative) {
            xhr.setRequestHeader('Accept-Encoding', 'gzip,deflate');
        }
        var isRaw = false;
        if (options && options.responseType) {
            isRaw = true;
            xhr.responseType = options.responseType;
            delete options.responseType;
        }
        _.forIn(options, function (value, key) {
            xhr.setRequestHeader(key, value);
        });
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if ((xhr.status >= 200 && xhr.status <= 207)) {
                    try {
                        if (isRaw) {
                            cbSucc(new Uint8Array(xhr.response));
                        } else {
                            cbSucc(xhr.responseText);
                        }
                    } catch (e) {
                        if (!cc.sys.isNative) {
                            cc.log(e.stack);
                        }
                        showAlert(e.message);
                    }
                } else {
                    if (!flag) {
                        flag = true;
                        cbFail(xhr.statusText, xhr.responseText);
                    }
                }
            }
        };
        xhr.onerror = function () {
            if (!flag) {
                flag = true;
                cbFail(xhr.status, null);
            }
        };
        xhr.send();
    },
    /**
     * post 请求
     * @param {String} url
     * @param {String|Object} data
     * @param {Function} ajaxSuccess
     * @param {Function} [ajaxError]
     * @param {Boolean} noBase64
     */
    post: function (url, data, ajaxSuccess, ajaxError, noBase64) {
        var flag = false;
        data = _.isString(data) ? data : JSON.stringify(data);
        var xhr = cc.loader.getXMLHttpRequest();
        xhr.open('POST', url);
        xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
        xhr.onreadystatechange = function () {
            var result, error = false;
            if (xhr.readyState == 4) {
                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || xhr.status == 0) {
                    var dataType = xhr.getResponseHeader('content-type');
                    result = xhr.responseText;
                    // cc.log(result);
                    try {
                        if (dataType.indexOf('json')) result = JSON.parse(result);
                    } catch (e) {
                        error = e;
                    }
                    if (error && !flag) {
                        flag = true;
                        ajaxError(error, 'parsererror', xhr);
                    } else {
                        ajaxSuccess(result, xhr);
                    }
                } else {
                    if (!flag) {
                        flag = true;
                        ajaxError(xhr.statusText || null, xhr.status ? 'error' : 'abort', xhr);
                    }
                }
            }
        };
        xhr.onerror = function () {
            if (!flag) {
                flag = true;
                ajaxError(xhr.statusText || null);
            }
        };
        if (noBase64) {
            xhr.send(data);
        } else {
            xhr.send(Base64.encode(data));
        }
    },
    /**
     * 上传声音文件
     * @param {String} filePath
     * @param {String} uploadFilename
     * @param {Function} cbSucc
     * @param {Function} cbFail
     */
    uploadFileToOSS: function (filePath, uploadFilename, cbSucc, cbFail) {
        if (!cc.sys.isNative) {
            return;
        }
        if (jsb.fileUtils.isFileExist(filePath)) {
            var data = jsb.fileUtils.getDataFromFile(filePath);
            var accessid = app.alov[2];
            var arr = app.alov[3];
            var host = app.alov[1];
            var subdir = app.alov[4] || '';
            var url = host + '/' + subdir + uploadFilename;
            var flag = false;
            var xhr = cc.loader.getXMLHttpRequest();
            xhr.open('PUT', url);
            xhr.setRequestHeader('Content-Length', data.length);
            var date = new Date().toGMTString();
            var contentMd5 = '';
            var contentType = 'application/x-www-form-urlencoded';
            var canonicalizedOSSHeaders = '';
            var canonicalizedResource = '/' + app.alov[0] + '/' + subdir + uploadFilename;
            var authStr = 'PUT\n'
                + contentMd5 + '\n'
                + contentType + '\n'
                + date + '\n'
                + canonicalizedOSSHeaders
                + canonicalizedResource;
            var auth = Crypto.util.bytesToBase64(Crypto.HMAC(Crypto.SHA1, authStr, arr.join(''), {asBytes: true}));
            xhr.setRequestHeader('Date', date);
            xhr.setRequestHeader('Content-Type', contentType);
            xhr.setRequestHeader('Authorization', 'OSS ' + accessid + ':' + auth);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        if (cbSucc)
                            cbSucc(url);
                    } else {
                        if (!flag) {
                            flag = true;
                            if (cbFail)
                                cbFail(xhr.statusText, xhr.responseText);
                        }
                    }
                }
            };
            xhr.onerror = function () {
                if (!flag) {
                    flag = true;
                    if (cbFail)
                        cbFail(xhr.status, null);
                }
            };
            xhr.send(data);
        }
    },
    /**
     * 上传错误log
     * @param {String} content
     */
    uploadErrorFileToOSS: function (content) {
        if (!cc.sys.isNative)
            return;
        var data = content;
        var time = timestamp2time(Math.round((new Date()).valueOf() / 1000));
        time = time.replace(/[\s:-]+/g, '_');
        // var uploadFilename = gameData.mapId + '-' + gameData.roomId + '-' + gameData.uid + '-' + time + '.txt';
        var uploadFilename = time + '_' + gameData.mapId + '-' + gameData.roomId + '-' + gameData.uid + '.txt';
        var accessid = app.alov[2];
        var arr = app.alov[3];
        var host = app.alov[1];
        var subdir = 'errorLog/' + app.area + '/';
        var url = host + '/' + subdir + uploadFilename;
        var xhr = cc.loader.getXMLHttpRequest();
        xhr.open('PUT', url);
        // xhr.setRequestHeader("Content-Length", data.length);
        var date = new Date().toGMTString();
        var contentMd5 = '';
        // var contentType = 'application/x-www-form-urlencoded';
        var contentType = 'text/html';
        var canonicalizedOSSHeaders = '';
        var canonicalizedResource = '/' + app.alov[0] + '/' + subdir + uploadFilename;
        var authStr = 'PUT\n'
            + contentMd5 + '\n'
            + contentType + '\n'
            + date + '\n'
            + canonicalizedOSSHeaders
            + canonicalizedResource;
        var auth = Crypto.util.bytesToBase64(Crypto.HMAC(Crypto.SHA1, authStr, arr.join(''), {asBytes: true}));
        xhr.setRequestHeader('Date', date);
        xhr.setRequestHeader('Content-Type', contentType);
        xhr.setRequestHeader('Authorization', 'OSS ' + accessid + ':' + auth);
        xhr.onreadystatechange = function () {
        };
        xhr.onerror = function () {
        };
        xhr.send(data);
    },
    /**
     * 下载头像
     * @param {String} url 头像地址
     * @param {cc.Sprite} targetSprite 头像节点
     * @param {Function} [successCb] 成功回调
     */
    downloadHeadImgToSprite: function (url, targetSprite, successCb) {
        if (isNullString(url)) {
            return;
        }

        if (url.charAt(url.length - 2) == '/' && url.charAt(url.length - 1) == '0') {
            url = url.substr(0, url.length - 2) + '/132';
        }
        var userData = targetSprite.getUserData() || {};
        if (userData.url == url)
            return;
        cc.textureCache.addImageAsync(url, function (texture) {
            var sprite = new cc.Sprite(texture);
            sprite.setTexture(texture);
            var scaleX = targetSprite.getContentSize().width / sprite.getContentSize().width;
            var scaleY = targetSprite.getContentSize().height / sprite.getContentSize().height;
            sprite.setScale(scaleX, scaleY);
            sprite.setAnchorPoint(0, 0);
            sprite.setName('head');
            if (!targetSprite.getChildByName('head'))
                targetSprite.addChild(sprite);
            userData.url = url;
            targetSprite.setUserData(userData);
            if (successCb)
                successCb();
        }, null);
    },
    /**
     * 是否是流量
     * @return {Boolean}
     */
    isWAN: function () {
        if (cc.sys.os == cc.sys.OS_IOS) {
            return jsb.reflection.callStaticMethod('NetManager', 'isWAN');
        } else if (cc.sys.os == cc.sys.OS_ANDROID) {
            return jsb.reflection.callStaticMethod(packageUri + '/utils/NetManager', 'isWAN', '()Z');
        }
        return true;
    },
    /**
     * 是否是wifi
     * @return {Boolean}
     */
    isWifi: function () {
        if (cc.sys.os == cc.sys.OS_IOS) {
            return jsb.reflection.callStaticMethod('NetManager', 'isWifi');
        } else if (cc.sys.os == cc.sys.OS_ANDROID) {
            return jsb.reflection.callStaticMethod(packageUri + '/utils/NetManager', 'isWifi', '()Z');
        }
        return true;
    }
});